package wangwenjun.phase2.concurrencypattern.eventrouter.demo01.framework;

import util.ThreadUtil;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author ChangLiang
 * @date 2020/6/20
 */
public class Router {

    private Queue<Event> eventQueue;

    public void addEvent(Event event) {
        synchronized (this) {
            eventQueue.add(event);
            this.notify();
        }
    }

    public Router(){
        eventQueue = new LinkedList<>();
        new Thread(()->processEvent(),"event-loop-thread").start();
    }

    public void processEvent() {
        while (true) {
            synchronized (this) {
                while (eventQueue.isEmpty()) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        ThreadUtil.exceptionToString(e);
                    }
                }
                Event event = eventQueue.remove();
                switch (event.getType()) {
                    case "A":
                        EventValve.handleEventA(event);
                    case "B":
                        EventValve.handleEventB(event);
                }
            }
        }
    }
}
